/**
 * 请求方法
 */
import axios, { CancelToken } from 'axios';
import qs from 'qs';
import { Dialog, Toast } from 'vant';

const pending = [];
let toastr = null;
const removePending = (config) => {
  for (const p in pending) {
    let tmp = `${config.url}@@${config.method}`;
    if (pending[p].u === tmp) {
      pending[p].f(`连续重复调用接口: ${tmp}，已取消多余请求`);
      pending.splice(p, 1);
    }
  }
};

// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    // 在一个请求发送前执行一下取消重复操作
    removePending(config);
    if (!/activity\/base\/info\/\d+$/.test(config.url)) {
      config.cancelToken = new CancelToken((c) => {
        pending.push({
          u: `${config.url}@@${config.method}`,
          f: c,
        });
      });
    }
    if (config.showLoading) {
      // toastr = Toast.loading();
      toastr = Toast.loading();
    }

    // 添加票据
    if (!config.headers.Authorization) {
      const token = window.token || null;
      if (token && !/getAppSign|getAuthUser|getCompanySign|queryAgentIdByCorpId|queryBuinessAppId/.test(config.url)) {
        config.headers.Authorization = `Bearer ${token}`;
      } else {
        delete axios.defaults.headers.common.Authorization;
      }
    }
    return config;
  },
  (error) => {
    if (toastr) {
      toastr.clear();
    }
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    removePending(response.config);
    // if (!pending.length && toastr) {
    //   toastr.clear();
    // }
    window.setTimeout(() => {
      if (!pending.length && toastr) {
        toastr.clear();
      }
    }, 500);
    return response;
  },
  (error) => {
    if (toastr) {
      toastr.clear();
    }
    // Toast.clear();
    return Promise.reject(error);
  }
);

const fetch = (options) => {
  let {
    method = 'post', // eslint-disable-line prefer-const
    data,
    url,
  } = options;
  method = method.toLowerCase();
  axios.defaults.baseURL = process.env.VUE_APP_API_BASE;
  axios.defaults.withCredentials = true;
  axios.defaults.crossDomain = true;
  axios.defaults.showDialog = true;
  axios.defaults.showLoading = true;
  // eslint-disable-next-line no-prototype-builtins
  if (options.hasOwnProperty('showDialog')) {
    axios.defaults.showDialog = options.showDialog;
  }
  // eslint-disable-next-line no-prototype-builtins
  if (options.hasOwnProperty('showLoading')) {
    axios.defaults.showLoading = options.showLoading;
  }

  const token = window.token || null;
  const corpID = window.corpID || null;
  const agentId = window.agentId || null;
  if (token && !/getAppSign|getAuthUser|getCompanySign|queryAgentIdByCorpId|queryBuinessAppId/.test(url)) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  } else {
    delete axios.defaults.headers.common.Authorization;
  }
  if (corpID) {
    axios.defaults.headers.common.corpId = corpID;
  }
  if (agentId) {
    axios.defaults.headers.common.agentId = agentId;
  }

  switch (method) {
    case 'get':
      return axios.get(url, {
        params: data,
      });
    case 'delete':
      return axios.delete(url, {
        data,
      });
    case 'post':
      return axios.post(url, data);
    case 'post-x-www-form-urlencoded':
      return axios.post(url, qs.stringify(data));
    case 'put':
      return axios.put(url, data);
    case 'patch':
      return axios.patch(url, data);
    default:
      return axios(options);
  }
};

// 错误日志
const addErrorLog = (resText, url, showDialog) => {
  let msg = resText;
  if (process.env.NODE_ENV === 'development') {
    try {
      let tmp = JSON.parse(resText);
      msg = process.env.NODE_ENV !== 'development' ? tmp.message || tmp.errmsg || tmp.msg : resText;
    } catch (e) {
      msg = resText;
    }
  }
  if (process.env.NODE_ENV === 'development') {
    console.error(`错误: 路径: ${url}, 返回值 : ${msg}`);
  }
  if (showDialog) {
    const { code, msg } = JSON.parse(resText);
    console.log('打印', msg);
    Dialog({ message: msg });
  }
};
const request = (options) => {
  return fetch(options)
    .then((res) => {
      const { data, status } = res;
      // 5003 还没有成为企业外部客户的新的C端用户登录
      if (status === 200 && (data.code === 200 || data.code === 5003)) {
        return data;
      }
      if (data.code === 1003 || data.msg === 'token过期') {
        res.data.msg += '，请刷新页面';
        sessionStorage.removeItem('wxUserInfo');
      }
      return Promise.reject({ response: res }); // 这样控制台会显示报错日志
    })
    .catch((error) => {
      if (error.request && error.request.status !== 200) {
        addErrorLog(error.request.statusText, error.request.responseURL, error.response.config.showDialog);
      } else if (error.response) {
        // 接口返回错误码是40029时，不弹框
        if (error.response.data.code !== 40029 && error.response.data.code !== 40163) {
          addErrorLog(
            error.response.request.responseText,
            error.response.request.responseURL,
            error.response.config.showDialog
          );
        }
      } else if (error && error.__CANCEL__) {
        console.warn(error);
        return Promise.reject({});
      } else {
        Dialog({ message: '未知错误' });
        console.error(error);
      }
      console.log(error.config);
      return Promise.reject(error.response.data || error.response || error);
    });
};

export default request;
